
#include <stdio.h>

#include <stdlib.h>

#include "cuda_runtime.h"

#include "device_launch_parameters.h"

#define	DATA_SIZE 1048567

int data[DATA_SIZE];

bool InitCUDA(){
	
	int	count;

	cudaGetDeviceCount(&count) ;

	if ( count == 0)
	{
		fprintf(stderr, "There is no device.\n") ;

		return false;
	}

	int	 i;

	for ( i = 0 ;i < count ; i++)
	{
		cudaDeviceProp prop ;

		if ( cudaGetDeviceProperties(& prop ,i) == cudaSuccess)
		{
			if ( prop.major >= 1)
			{
				break;
			}
		}
	}
		if ( i == count)
		{
			fprintf(stderr ,"There is no device supporting CUDA1.x.\n");

			return false;
		}

		cudaSetDevice( i );

		return true;
	
}

void	generateNumbers(int* data, int size){

	
	for (int i = 0; i < size; i++)
	{
		data[i] = rand()%10;
	}
}

__global__ static void sumofSquares(int* num, int* result){

	int sum = 0;
	for(int i = 0 ;i < DATA_SIZE; i++){

		sum += num[i]*num[i];
	}

	*result = sum;
}
int main(){

	if (! InitCUDA())
	{
		return 0;
	}

	printf("Hello word ,cuda has been initialized.\n");

	generateNumbers(data,DATA_SIZE);

	int* gpudata,*gpu_result;

	cudaMalloc((void**)&gpudata, sizeof(int)*DATA_SIZE);

	cudaMalloc((void**)&gpu_result, sizeof(int));

	cudaMemcpy(gpudata, data,sizeof(int)*DATA_SIZE,cudaMemcpyHostToDevice);

	sumofSquares<<<1, 1, 0>>>(gpudata,gpu_result);

	int sum = 0;

	cudaMemcpy(&sum	,gpu_result,sizeof(int),cudaMemcpyDeviceToHost);

	printf("sum(gpu)=%d\n", sum	);

	sum = 0;
	for (int i = 0 ;i < DATA_SIZE; i++)
	{
		sum	+= data[i]*data[i];

	}

	printf("sum(cpu)=%d\n",sum);
	return 0;
}